$(function() {
    $category.init();
});

$tree = function() {
    var $menu = {
        list: null,
        li: '',
        _init: function($list, $li) {
            this.list = $list;
            this.li = $li;
        },
        findIndex: function($start, $parentId) {
            for (var $i = $start; $i < this.list.length; $i++) {
                if (this.list[$i].parent_id == $parentId) {
                    return $i;
                }
            }

            return -1;
        },
        getli: function($parentId, $index) {
            var $tree = '';

            for (var $i = $index; $i < this.list.length; $i++) {
                if (this.list[$i].parent_id != $parentId) {
                    return $tree;
                }

                if (this.list[$i].parent_id == $parentId) {
                    var $name = this.list[$i].name;
                    var $subIndex = this.findIndex($i, this.list[$i].id);
                    var $subtree = '';

                    if ($subIndex != -1) {
                        $subtree = this.getli(this.list[$i].id, $subIndex);
                    }

                    $tree += this.li.replace(/{category}/g, $name);
                    $tree = $tree.replace(/{category_id}/g, this.list[$i].id);

                    if ($subtree) {
                        $tree = $tree.replace(/{sub_category}/g, '<ul>' + $subtree + '</ul>');
                        $tree = $tree.replace(/{@|@}/g, '');
                    }
                    else {
                        $tree = $tree.replace(/{sub_category}/g, '');
                        $tree = $tree.replace(/{@.*@}/g, '');
                    }
                }
            }

            return $tree;
        },
        render: function($list, $parentId, $index, $ul, $li) {
            this._init($list, $li);
            return $ul.replace(/{li_content}/g, this.getli($parentId, $index));
        }
    };

    return $menu;
}();

var $category = function() {
    var $cat = {
        fields: {
            name: 'category_name',
            description: 'category_description'
        },
        init: function() {
            this._initDialog()
                    ._initEvent()
                    ._initCategoryList();
        },
        _initDialog: function() {
            //Message add when not choose any category.
            $('#dg_confirm_add').dialog({
                autoOpen: false,
                width: 400,
                height: 200,
                modal: true,
                buttons: {
                    Ok: function() {
                        $category.add();
                        $(this).dialog('close');
                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });

            //Dialog delete product
            $('#dialog_del_product').dialog({
                autoOpen: false,
                width: 500,
                height: 400,
                modal: true,
                buttons: {
                    Ok: function() {
                        $product.deleteProducts();
                    },
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
            return this;
        },
        _initCategoryList: function() {
            this.gets();
            //product category tree view
            $("#product_category_tree").treeview();

            return this;
        },
        _initEvent: function() {
            //Initialize dialog upload image when add new product.
            $('input#save_category').click(function() {
                $category.resetFieldAdd();
                $('#category_parent_id').val($('input:radio[name=category]:checked').val());
                
                if (!$('#category_parent_id').val()) {
                    $('#dg_confirm_add').dialog('open');
                    return false;
                }

                $category.add();
            });

            $('.edit-category').live('click', function($event){
                $event.preventDefault();
                $category.resetFieldAdd();
                $id = $(this).attr('id').replace('edit_category_', '');
                $('#category_id').val($id);
                $category.getById($id);
            });
            
            return this;
        },
        refresh: function() {
            this.gets();
            return this;
        },
        proccessErrorAdd: function($aError) {
            this.resetFieldAdd();

            for ($error in $aError) {
                $('#' + $category.fields[$error])
                        .after($aError[$error])
                        .css('border', '1px solid red');

                if (!$aError[$error]) {
                    $('#' + $category.fields[$error])
                            .css('border', '');
                }
            }
        },
        resetFieldAdd: function() {
            $('#category_success_message').empty();
            for ($field in $category.fields) {
                $('#' + $category.fields[$field]).css('border', '');
                $('#' + $category.fields[$field] + '+ div.error').remove('div.error');
            }
        },
        gets: function() {
            var $li = $('#li_category').html().toString();
            $li = $li.replace('<!--', '').replace('-->', '');
            var $ul = '<ul id="product_category_tree" class="filetree treeview-famfamfam">{li_content}</ul>';

            var $option = {
                type: 'post',
                url: $tut.siteUrl('category/admincp/index/gets'),
                dataType: 'json',
                data: '',
                success: function($response, $status) {
                    if ($response.result) {
                        $('#tree_category').empty().append($tree.render($response.data, 0, 0, $ul, $li));
                    }
                }
            };

            $tut.ajax($option);
            return this;
        },
        deleteProduct: function() {
            var $class = $('.product-select');
            var $ids = '{';

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $ids += '"' + $item + '":"' + $class[$item].id + '",';
                }
            }

            $ids = $ids.replace(/,$/g, '') + '}';
            var $curPage = $('#current_page_product').text();
            $curPage = !$curPage ? 1 : $curPage;

            var $option = {
                type: 'post',
                url: $tut.siteUrl('product/admincp/index/delete'),
                dataType: 'json',
                data: {product_ids: $ids, cur_page: $curPage},
                success: function($response, $status) {
                    if ($response.result) {
                        //Close dialog confirm.
                        $('#dialog_del_product').dialog('close');
                        //Get list product of page.
                        ///////////////////////////
                        $page.get($response.data.page);
//                    $product.getList($response.data.page);
                    }
                }
            };

            $tut.ajax($option);

            return this;
        },
        showDeletedItems: function() {
            var $class = $('.product-select');
            var $listDeleted = '';

            for (var $item in $class) {
                if ($class[$item].checked == true) {
                    $listDeleted += '<li class="deleted-product">' + $('#product_name_' + $class[$item].id).text() + '</li>';
                }
            }

            //if no product is deleted that isn't show dialog.
            if ($listDeleted) {
                //Show dialog delete product.
                $('#dialog_del_product').dialog('open');
                //Append to section deleted product dialog.
                $('#list_deleted_product').append($listDeleted);
            }

            return this;
        },
        resetDeletedItems: function() {
            return this;
        },
        getById: function($id) {
            var $option = {
                type: 'post',
                url: $tut.siteUrl('category/admincp/index/get'),
                dataType: 'json',
                data: {category_id: $id},
                success: function($response, $status) {
                    if ($response.result) {
                        //populate product into edit form. and set useful.
                        $category.populate($response.data);
                    }
                }
            };

            $tut.ajax($option);

            return this;
        },
        populate: function($data) {
            for (var $field in $data) {
                $('#' + this.fields[$field]).val($data[$field]);
            }
            
            $('#category_status_1').prop('checked', true);
            
            if($data.is_actived == 0){
                $('#category_status_2').prop('checked', true);
            }
            
            if($data.parent_id){
                $('input:radio[id=category_' + $data.parent_id + ']').prop('checked',true);
            }
            
            ////mutiple language.../////////////////////////////////////
            $('#save_category').val('Update');
            return this;
        },
        add: function() {
            var $option = {
                type: 'post',
                url: $('#form_add_category').attr('action'),
                dataType: 'json',
                data: $('#form_add_category').serialize(),
                success: function($response, $status) {
                    if ($response.result) {
                        //Reset form to empty.
                        $('#form_add_category').get(0).reset();
                        //Refresh list category.
                        $category.resetFieldAdd();
                        //Output message successfully.
                        $("#category_success_message").html($response.message);
                        $category.gets($response.data);
                        ///////////////////////////////
                        $('#save_category').val('Add');
                    }
                    else {
                        $category.proccessErrorAdd($response.data);
                    }
                }
            };

            $tut.ajax($option);
            return this;
        }
    };



    $cat.Match = function()
    {
        alert('match');
    };

    $cat.Match.prototype.toString = function()
    {
        return this.value;
    };

    $cat.prototype = {
        a: function() {
        },
        b: function() {
            alert('b');
        },
        c: function() {
        }
    };


    return $cat;
}();